//
// Created by 11510 on 2024/6/12.
//
#include <iostream>
using std::cout;
using std::cin;
using std::endl;


class Data{
public:
    Data(){
        printf("Data()\n");
    }
    ~Data(){
        printf("~Data()\n");
    }
    int getData() const{
        return _data;
    }

private:
    int _data = 10;
};


class MiddleLayer{
public:
    MiddleLayer(Data * p): _pdata(p){
        printf("MiddleLayer()\n");
    }

    ~MiddleLayer(){
        printf("~MiddleLayer\n");
        if(_pdata){
            delete _pdata;
            _pdata = nullptr;
        }
    }

    /**
     * 重载->
     * @return
     */
    Data* operator->(){
        return _pdata;
    }

    /**
     * 重载*
     * @return
     */
    Data& operator*(){
        return *_pdata;
    }

private:
    Data * _pdata;
};



void test0(){
    Data* data = new Data();
    cout << data->getData() << endl;

    MiddleLayer middleLayer(data);

    /* 再delete会有double free*/
//    delete data;
}

void test1(){
    Data* data = new Data();
//    cout << data->getData() << endl;
    delete data;


    /**
     * 只能指针雏形
     * 利用局部对象的生命周期来回收其托管的资源
     * middeLayer是一个对象，但完全可以像原生Data*一样使用
     * 同时，middleLayer对象的销毁还可以对堆空间资源自动回收
     */
    MiddleLayer middleLayer(new Data());

    (middleLayer.operator->())->getData();// 本质
//    cout << middleLayer->getData() << endl;

    (*middleLayer).getData();//本质
    cout << (*middleLayer).getData() << endl;
}

int main() {
    test1();
    return 0;
}